package com.tolerate.managespringboot.config.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tolerate.managespringboot.entity.User;
import com.tolerate.managespringboot.exception.BusinessException;
import com.tolerate.managespringboot.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserServiceImpl userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 执行认证
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(401, "无token，请重新登录");
        }

        String userId;
        try {
            // 获取 token 中的 user id
            userId = JWT.decode(token).getAudience().get(0);
        } catch (Exception e) {
            throw new BusinessException(401, "token验证失败，请重新登录");
        }

        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(401, "用户不存在，请重新登录");
        }
        // 用户名称加签验证 token
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(user.getUsername())).build();
        try {
            DecodedJWT decodedJWT = verifier.verify(token);
            String tokenUserId =decodedJWT.getAudience().get(0);
            if (!userId.equals(tokenUserId)) {
                throw new BusinessException(401, "token验证失败，请重新登录");
            }
        } catch (Exception e) {
            throw new BusinessException(401, "token验证失败，请重新登录");
        }
        return true;
    }
}
